import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import type { RootState } from './store'

export const counterSlice = createSlice({
    name: 'counter',
    // `createSlice` 将从 `initialState` 参数推断 state 类型
    initialState: {
        // 收藏
        collect: JSON.parse(localStorage.getItem('collect') || '[]') as any,
        // 关注
        follow: JSON.parse(localStorage.getItem('follow') || '[]') as any,
    },
    reducers: {
        collect(state, { payload }) {
            const item = state.collect.find((item: any) => {
                return item.id === payload.id;
            })
            // 如果存在删除
            if (item) {
                item.show = true;
            } else {
                state.collect.push({ ...payload, show: false });
            }

            localStorage.setItem('collect', JSON.stringify(state.collect))
        },

        // 取消收藏
        closeUncollect(state, { payload }) {

            state.collect = state.collect.filter((item:any) => {
                return item.id !== payload.id;
            });
            localStorage.setItem('collect', JSON.stringify(state.collect))
        },

        // 状态
        collectStatus(state, { payload }) {
            const item = state.collect.find((item: any) => {
                return item.id === payload.id;
            })
            if (item) {
                item.flag = !item.flag;
            }
            localStorage.setItem('collect', JSON.stringify(state.collect))
        },


        // 关注
        Addfollow(state, { payload }) {
            const item = state.follow.find((item: any) => {
                return item.id === payload.id;
            })
            if (item) {
                item.flag = !item.flag
            } else {
                state.follow.push({ ...payload, flag: true })
            }
            localStorage.setItem('follow', JSON.stringify(state.follow));
        },

        // 取消关注
        unfollow(state, { payload }) {
            state.follow = state.follow.filter((item: any) => {
                return item.id !== payload.id
            })
            localStorage.setItem('follow', JSON.stringify(state.follow));
        },


    }
})

export const { collect, closeUncollect, collectStatus, Addfollow, unfollow } = counterSlice.actions
export default counterSlice.reducer
